const express = require('express')
const router = express.Router();
const UrlModel = require('../models/Url')
const validUrl = require('valid-url')
const shortid = require('shortid')
const config = require('config')


// 延时
async function sleep(time){
    return new Promise((resolve, reject) =>{
        let timer=setTimeout(()=>{
            resolve()
            clearTimeout(timer)
        },time*1000)
    })
}

// @route POST api/url/shorten
// @desc 创建短链接

router.post('/shorten', async (req, res) => {

    await sleep(2)
    // 相关逻辑
    // 1.获取长链接
    const { longUrl } = req.body;
    // 2.验证长连接
    console.log(longUrl)
    if (!validUrl.isUri(longUrl)) {
        return res.status(401).json("无效Url")
    }

    // 3.生成url code
    const urlCode = shortid.generate()
    // 4.生成短链接
    const shortUrl = config.get('baseUrl') + urlCode

    try {
        // 验证长连接是否已经存在数据库
        let url = await UrlModel.findOne({ longUrl })
        if (url) {
            
            return res.json(url);
        }
        // 写入数据库
        url = new UrlModel({
            longUrl, shortUrl, urlCode, date: new Date()
        })
        url.save()
       return res.json(url)
    } catch (error) {
        console.error(error)
       return res.status(500).json('Server error.')
    }
})

module.exports = router